<template>
    <div>
      <div class="receipt-order-edit-wrapper app-container" style="margin-bottom: 60px" v-loading="loading">
        <el-card header="订单基本信息">
          <el-form label-width="108px" :model="form" ref="receiptForm" :rules="rules">
            <el-row :gutter="24">
              <el-col :span="11">
                <el-form-item label="订单单号" prop="order_id">
                  <el-input class="w200" v-model="form.order_id" placeholder="订单单号" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="仓库" prop="warehouseId">
                  <el-select v-model="form.warehouseId" placeholder="请选择仓库" filterable>
                    <el-option v-for="item in useWmsStore().warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="6">
                <el-form-item label="总数量" prop="totalQuantity">
                  <el-input-number style="width:100%" v-model="form.totalQuantity" :controls="false" :precision="0" :disabled="true"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="11">
                <el-form-item label="订单类型" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio-button
                      v-for="item in wms_shipment_status"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio-button
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="供应商" prop="merchantId">
                  <el-select v-model="form.merchantId" placeholder="请选择供应商" clearable filterable>
                    <el-option v-for="item in useWmsStore().merchantList" :key="item.id" :label="item.merchantName" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="6">
                <el-form-item label="客户名称" prop="customer">
                  <el-input v-model="form.customer" placeholder="请输入客户名称" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="11">
                <el-form-item label="备注" prop="remarks">
                  <el-input
                    v-model="form.remarks"
                    placeholder="备注...100个字符以内"
                    rows="4"
                    maxlength="100"
                    type="textarea"
                    show-word-limit="show-word-limit"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <div style="display: flex;align-items: start">
                  <el-form-item label="下单日期" prop="order_date">
                    <el-input type="date" v-model="form.order_date" :disabled="true"/>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card header="订单明细" class="mt10">
          <div class="receipt-order-content">
            <div class="flex-space-between mb8">
              <el-popover
                placement="left"
                title="提示"
                :width="200"
                trigger="hover"
                :disabled="form.order_id"
                content="请先输入订单单号！">
              </el-popover>
            </div>
            <el-table :data="form.detail" border empty-text="暂无订单明细">
              <el-table-column label="产品ID">
                <template #default="{ row }">
                  <div>{{ row.product_id }}</div>
                </template>
              </el-table-column>
              
              <el-table-column label="产品名称">
                <template #default="{ row }">
                  <el-select v-model="row.product_id" :disabled="true">
                    <el-option v-for="option in optionList" :value="option.id" :key="option.id" :label="option.text" >
                      {{ option.text }}
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="quantity">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.quantity"
                    placeholder="数量"
                    :min="1"
                    :precision="0"
                    :disabled="true"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="库存数量" prop="Inventory">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.Inventory"
                    placeholder="0"
                    :min="1"
                    :precision="0"
                    :disabled="true"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="100" align="right" fixed="right">
                <template #default="scope">
                  <el-button icon="Delete" type="danger" plain size="small" @click="handleDeleteDetail(scope.row, scope.$index)" link :disabled="true">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
      <div class="footer-global">
        <div class="btn-box">
          <div>
            <el-button @click="doWarehousing" type="primary" class="ml10">完成审核</el-button>
          </div>
          <div>
            <el-button @click="cancel" class="mr10">取消</el-button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup name="ReceiptOrderEdit">
  import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
  import {ElMessage} from "element-plus";
  import {useRoute} from "vue-router";
  import {generateNo } from '@/api/wms-order/NewOrderId'
  // import {delReceiptOrderDetail } from '@/api/wms/receiptOrderDetail'
  import {getorderdata, UpdateOrder, CreateOrder ,Getdatebound} from "@/api/wms-order/product"
  import {ProductList} from "@/api/wms-django/product/product"
  
  const {proxy} = getCurrentInstance();
  
  const wms_shipment_status = ref([
    {
      label: '未审核',
      value: '-1'
    },
    {
      label: '未出库',
      value: '0'
    },
    // {
    //   label: '已出库',
    //   value: '1'
    // },
    {
      label: '作废',
      value: '2'
    },
    {
      label: '驳回',
      value: '3'
    }
  ])
  const selectedSku = ref([])
  const loading = ref(false)
  const NewData = ref(false)
  const initFormData = {
    order_id: undefined,
    status: "-1",
    // merchantId: undefined,
    customer: undefined,
    order_date: undefined,
    orderStatus: 0,
    remarks: undefined,
    // warehouseId: undefined,
    totalQuantity: 0,//总数量
    detail: [],
  }
  
  const data = reactive({
    form: {...initFormData},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      order_id: undefined,
      status: undefined,
      customer: undefined,
      remarks: undefined,
      order_date: undefined,
      orderStatus: undefined,
    },
    rules: {
      order_id: [
        {required: true, message: "订单单号不能为空", trigger: "blur"}
      ],
      // warehouseId: [
      //   {required: true, message: "请选择仓库", trigger: ['blur', 'change']}
      // ]
    }
  });
  const { form, rules} = toRefs(data);
  
  const cancel = async () => {
    await proxy?.$modal.confirm('确认取消编辑订单吗？');
    close()
  }
  const close = () => {
    const obj = {path: "/OrderBy"};
    proxy?.$tab.closeOpenPage(obj);
  }

  // 初始化receipt-order-form ref
  const receiptForm = ref()
  
  const getParamsBeforeSave = () => {
    let Returndetails = []
    let Inputname
    form.value.detail.product_name = optionList.value.product_name
    if (form.value.detail?.length) {
      Returndetails = form.value.detail.map(it => {
        for(let i = 0; i < optionList.value.length; i++){
          if(optionList.value[i].id === it.product_id){
            Inputname = optionList.value[i].text
          }
        }
        const base = {
          product_id: it.product_id,
          product_name: Inputname,
          // order_id: it.order_id,
          quantity: it.quantity,
          // warehouseId: form.value.warehouseId,
        }
        return it.detail_id ? { ...base, detail_id: it.detail_id } : base
      })
    }
  
    return {
      order_id: form.value.order_id,
      status: form.value.status,
      // merchantId: form.value.merchantId,
      customer: form.value.customer,
      remarks: form.value.remarks,
      order_date: form.value.order_date,
      totalQuantity: form.value.totalQuantity,
      // warehouseId: form.value.warehouseId,
      detail: Returndetails
    }
  }
  
  
  const doWarehousing = async () => {
    await proxy?.$modal.confirm('确认修改订单吗？');
    receiptForm.value?.validate((valid) => {
      // 校验
      if (!valid) {
        return ElMessage.error('请填写必填项')
      }
      const params = getParamsBeforeSave();

      loading.value = true
      if(NewData.value){
        CreateOrder(params).then((res) => {
          if (res.status === 201) {
            ElMessage.success('订单添加成功')
            close()
          } else {
            ElMessage.error(res.msg)
          }
          }).finally(() => {
            loading.value = false
          })
        } else {
        UpdateOrder(params.order_id ,params).then((res) => {
          if (res.status === 200) {
            ElMessage.success('订单修改成功')
            close()
          } else {
            ElMessage.error(res.msg)
          }
          }).finally(() => {
            loading.value = false
          })
      }
    })
  }
  
  const route = useRoute();
  onMounted(() => {
    const id = route.query && route.query.id;
    if (id) {
      loadDetail(id)
    } else {
      form.value.order_id = generateNo()
      NewData.value = true
    }
  })
  
  // 获取订单详情
  const loadDetail = (query) => {
    loading.value = true
    getorderdata(query).then((response) => {
      form.value = {...response.data}
      if (response.data.detail?.length) {
        selectedSku.value = response.data.detail.map(it => {
          return {
            id: it.skuId
          }
        })
      }
      Promise.resolve();
    }).then(() => {
    }).finally(() => {
      loading.value = false
      let sum = 0
      for(let i = 0 ; i<form.value.detail.length ; i++){
        sum += Number(form.value.detail[i].quantity)
      }
      form.value.totalQuantity = sum
      GetInventory()
    })
  }
  
  const GetInventory = () =>{
    let a = ''
    for(let i =0; i < form.value.detail.length ; i++){
      a = a + form.value.detail[i].product_id + ','
    }
    Getdatebound({id : a}).then((response) =>{
      for( let i = 0; i < form.value.detail.length; i++){
        for( let j = 0; j < response.data.results.length; j++){
          if(form.value.detail[i].product_id === response.data.results[j].product.productId){
            form.value.detail[i].Inventory = response.data.results[j].quantity
          }
        }
      }

      // console.log(response.data.results[0].quantity)
      // form.value.Inventory = response.data.results[0].quantity
      // console.log(form.value.Inventory)
    })
  }

  // 画面删除
  const handleDeleteDetail = (row, index) => {
    form.value.detail.splice(index, 1)
    const indexOfSelected = selectedSku.value.findIndex(it => row.product_id=== it.product_id)
    selectedSku.value.splice(indexOfSelected, 1)
  }
  
  // 获取产品信息
  const optionList = ref([]);
  
  const GetoptionList = () =>{
    ProductList().then(
      res => {
        res.data.forEach(element => {
          optionList.value.push({
            id: element.product_id,
            text: element.product_name
          })
        })
      }
    )
  }
  GetoptionList()
  
  
  </script>
  
  <style lang="scss" scoped>
  @import "@/assets/styles/variables.module";
  
  .btn-box {
    width: calc(100% - #{$base-sidebar-width});
    display: flex;
    align-items: center;
    justify-content: space-between;
    float: right;
  }
  </style>
  